//
//  FilePath.swift
//  yiplayer
//
//  Created by cgw on 2024/5/10.
//

import Foundation

class YiFilePath: NSObject{
    
    static let share = YiFilePath()
    
    // 歌曲目录
    lazy var songDir: String = {
        return self.docmentPath("songs").toPath() ?? ""
    }()

    private func docmentPath(_ appendingPath: String) -> URL{
        let cachesDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let dir = cachesDirectory.appendingPathComponent(appendingPath)
        self.createDirectoryIfNeeded(directory: dir)
        
        return dir
    }
    
    private func createDirectoryIfNeeded(directory: URL) {
        if let path = directory.toPath() {
            if FileManager.default.fileExists(atPath: path) {
                return
            }
        }
        do {
            try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: nil)
        } catch {
            print("Failed to create cache directory: \(error)")
        }
    }

    //歌曲目录: 每个歌曲都创建一个同名目录，存放mp3\jpg\lrc文件
    private func songDir(songFullName: String?) -> String? {
        if let fn = songFullName {
            let dir = self.songDir+"/"+fn
            if let ul = dir.toFileUrl() {
                self.createDirectoryIfNeeded(directory: ul)
                return dir
            }
        }
        return nil
    }
    
    //歌曲全路径
    func songFilePath(songFullName: String?, ext: String) -> String?{
        if let dir = songDir(songFullName: songFullName) {
            return dir+"/"+songFullName!+"."+ext
        }
        return nil
    }
    
    func lyricFilePath(songFullName: String?) -> String?{
        return songFilePath(songFullName: songFullName, ext: "lrc")
    }
    
    func coverFilePath(songFullName: String?) -> String?{
        return songFilePath(songFullName: songFullName, ext: "jpg")
    }
}

extension String {
    func toUrl() -> URL?{
        return URL.init(string: self)
    }
    
    func toFileUrl() -> URL? {
        return NSURL.init(fileURLWithPath: self) as URL
    }
    
    func appendPath(pathname:String) -> String{
        return self + "/" + pathname
    }
}

extension URL {
    func toPath() -> String?{
        let url = self as NSURL
        if url.isFileURL {
            return url.path
        }else{
            return url.absoluteString
        }
    }
}
